from net_controller import *
from optparse import OptionParser

import re
import sys

class ByouClient:

    def __init__(self, proc_id, cmd_filename, options, config_path="config.json"):
        self.cmd_id = 0
        self.cmd_list = open(cmd_filename).readlines()
        self.delay = options.delay
        self.max_retry = 12
        self.nc = NetController(proc_id, None, config_path)
        self.proc_id = proc_id
        self.server_id = 0
        self.timeout = 5
        self.verbose = options.verbose

    def parse_command(self, cmd_string):
        cmd = {"cmd_id" : self.cmd_id, "proc_id" : self.proc_id}

        results = re.split('\W+', cmd_string)

        if results[0] == "add":
            cmd["type"] = results[0]
            cmd["key"] = results[1]
            cmd["url"] = results[2]

        elif results[0] == "delete":
            cmd["type"] = results[0]
            cmd["key"] = results[1]

        elif results[0] == "edit":
            cmd["type"] = results[0]
            cmd["key"] = results[1]
            cmd["url"] = results[2]

        elif results[0] == "print":
            cmd["type"] = results[0]

        return cmd

    def run(self):
        print "Running client..."

        while True:
            if self.cmd_list:
                self.cmd_id += 1

                cmd_string = self.cmd_list.pop(0).rstrip('\n')
                print "Reading: " + str(cmd_string)

                cmd = self.parse_command(cmd_string)

                if self.verbose: print "Sending: " + str(cmd)
                nc_return = self.send_command(cmd)

                print "Receive: " + str(nc_return) + "\n"

                time.sleep(self.delay)

    def send(self, msg):
        self.nc.send(self.server_id, msg, self.delay)

    def send_command(self, cmd):
        self.send(cmd)

        nc_return = self.nc.next(True, self.timeout)

        while True:
            
            nc_return = self.nc.next(True, self.timeout)

            if nc_return != None:
                return nc_return
            else:
                self.send(cmd)

if __name__ == "__main__":

    usage = "usage: %prog [options] proc_id command_file"
    parser = OptionParser(usage=usage)

    parser.add_option("-d", "--delay", default=0, dest="delay",
                      help="set message delay", metavar="<n>", type="int")
    parser.add_option("-v", "--verbose", default=False, dest="verbose", action="store_true",
                      help="verbose output")

    (options, args) = parser.parse_args()

    if len(args) < 2:
        parser.print_help()
        sys.exit(1)

    print "cmd_file = ", args[1]
    print "delay =    ", options.delay
    print "proc_id =  ", args[0]

    client = ByouClient(int(args[0]), args[1], options)
    client.run()